package com.yq.cp.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.yq.cp.config.UserThreadLocal;
import com.yq.cp.entity.permission.User;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Log4j2
@Component
public class FileUploadUtli {

    public static String ALIYUN_ACCESS_ID="LTAI5tK5GQMwo4zDGjrNvGUv";
    public static String ALIYUN_ACCESS_KEY="QQTmmPHECb4TLSWQ5cSdsY9MN1oGWS";
    @Value("${upload.path}")
    private String path="";
    @Value("${upload.domain}")
    private String domain="";


    /**
     * 生成图片保存路径
     *
     * @param file 图片
     * @return 路径
     */
    private String buildImgPath(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();

        return new SimpleDateFormat("yyyy/MM/dd/")
                .format(DateTimeUtil.dqsj()) + UUID.randomUUID() + "." +
                Objects.requireNonNull(originalFilename.split("\\.")[1]);
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 文件访问地址
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    public String uploadFile(MultipartFile file) {
        try {
            String fileName = this.buildImgPath(file);
            File saveFile = new File(path + "/" + fileName);
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            file.transferTo(saveFile);
            return domain + "/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 上传文件
     *
     * @param files 文件
     * @return 文件访问地址
     */
    public List<String> uploadFileList(MultipartFile[] files) {
        if (files == null || files.length < 1) {
            return null;
        }
        List<String> list = new ArrayList<>();
        for (MultipartFile file : files) {
            list.add(this.uploadFile(file));
        }
        return list;
    }

    private String buildImgPathAly(MultipartFile file) {

        return file.getOriginalFilename().split("\\.")[0]+RandomUtil.b(100)+ "." +
                Objects.requireNonNull(file.getOriginalFilename()).split("\\.")[file.getOriginalFilename().split("\\.").length-1];
    }


    public  String aly(MultipartFile file){
        String fwlj="https://yinlangpai.oss-cn-chengdu.aliyuncs.com/";
        String originalFilename = file.getOriginalFilename();
        if (originalFilename.contains(".apk")){
            String endpoint2="";
            fwlj=endpoint2;
        }

        String fileName = this.buildImgPathAly(file);
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";

        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ALIYUN_ACCESS_ID;
        String accessKeySecret = ALIYUN_ACCESS_KEY;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "yinlangpai";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        User user = UserThreadLocal.get();
        if (user!=null){
            fileName=user.getId()+"/"+fileName;
        }else {
            fileName="00000000"+"/"+fileName;
        }
        String objectName = "ht/"+fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            File file1 = multiPartFileToFile(file);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file1);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            file1.delete();

            return fwlj+objectName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            System.out.println("Error Message:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "";
    }

    public  String alyBcxcxm(String address){

        File file1 = new File(address);
        String fwlj="https://yinlangpai.oss-cn-chengdu.aliyuncs.com/";

        String fileName=file1.getName();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";

        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ALIYUN_ACCESS_ID;
        String accessKeySecret = ALIYUN_ACCESS_KEY;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "yinlangpai";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        User user = UserThreadLocal.get();
        if (user!=null){
            fileName=user.getId()+"/"+fileName;
        }else {
            fileName="00000000"+"/"+fileName;
        }
        String objectName = "ht/"+fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file1);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            file1.delete();

            return fwlj+objectName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (Exception e) {
            System.out.println("Error Message:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "";
    }
    /**
     * MultipartFile转File
     * <p>
     * 项目根路径创建临时文件，转换得到File，再删除临时文件
     *
     * @param multipartFile
     * @return
     */
    public static File multiPartFileToFile(MultipartFile multipartFile) throws IOException {

        //获取文件名
        String originalFilename = multipartFile.getOriginalFilename();

        //获取默认定位到的当前用户目录("user.dir"),也就是当前应用的根路径
        String tempDir = System.getProperty("user.dir");

        //根目录下生成临时文件
        File file = new File(tempDir+File.separator+originalFilename);

        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);

        return file;
    }

    public void deleteFile(String url) {
        // 创建OSSClient实例（OSS客户端实例）
        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";
        String bucketName = "yinlangpai";

        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ALIYUN_ACCESS_ID;
        String accessKeySecret = ALIYUN_ACCESS_KEY;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        //文件名（服务器上的文件路径）
        String host="https://yinlangpai.oss-cn-chengdu.aliyuncs.com/";
        String objectName = url.substring(host.length());

        // 判断是否删除成功
        boolean deleteFileSucceed = false;

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, objectName);

            deleteFileSucceed = true;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static void main(String[] args) {
        FileUploadUtli fileUploadUtli=new FileUploadUtli();
        fileUploadUtli.deleteFile("https://yinlangpai.oss-cn-chengdu.aliyuncs.com/yinlang/ht/5fn8jNnK5dCrYJDzc3Y38tB8wFf8TNNp.mp3");
    }

}

